﻿using System.IO;
using System.Linq;
using System.Xml.Linq;
using FitNesseRunner.Model;

namespace FitNesseRunner
{
	class FolderTypeResolver : IFolderTypeResolver
	{
		public FolderType GetFolderType(DirectoryInfo directoryInfo)
		{
			var propertiesXml = LoadPropertiesXml(directoryInfo.FullName);
			if (propertiesXml == null)
				return FolderType.Suite;

			var elementNames = from element in propertiesXml.Root.Elements()
			                   select element.Name.LocalName;

			if (elementNames.Contains("Suite"))
				return FolderType.Suite;

			if (elementNames.Contains("Test"))
				return FolderType.Test;

			return FolderType.None;
		}

		private static XDocument LoadPropertiesXml(string path)
		{
			var propertiesFilePath = Path.Combine(path, "Properties.xml");
			return File.Exists(propertiesFilePath)
			       	? XDocument.Load(propertiesFilePath)
			       	: null;
		}
	}
}
